from django.shortcuts import render,HttpResponse
from websocket import WebsocketServer
from threading import Thread
# import json
client_list=[]
def thread_it(func, *args):#多线程函数
    t = Thread(target=func, args=args)
    t.setDaemon(True)
    t.start()


def new_client(client, server):
    print("New client connected and was given id %d" % client['id'])
    #server.send_message_to_all("a new client...")
    global client_list
    client_list.append(client)
    server.send_message(client,"你已经成功连接聊天室，现在可以开始聊天了")


# Called for every client disconnecting
def client_left(client, server):
    print("Client(%d) disconnected" % client['id'])
    global client_list
    client_list.remove(client)

# Called when a client sends a message
def message_received(client, server, message):
    global client_list
    print(f"用户列表:{client_list}")
    for i in client_list:
        server.send_message(i, f'ip:{client["address"]}的用户{client["id"]}说:{message}')
def runwebsocket():
    PORT = 9001
    server = WebsocketServer(PORT, host="127.0.0.1")
    server.set_fn_new_client(new_client)
    server.set_fn_client_left(client_left)
    server.set_fn_message_received(message_received)
    server.run_forever()

def index(requests):
    return render(requests,'client.htm')

thread_it(runwebsocket)